package com.lz.yz.outing.service;

import com.lz.yz.base.util.DateHelper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class CreateNo {

    public static long today_rank = 0L;

    @Resource(name = "redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 调整利用redis事务控制数据唯一性
     *
     * @return
     */
    public long getTodayRank() {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        if (ops.get(todayRankKey()) == null) {
            ops.set(todayRankKey(), today_rank,1, TimeUnit.DAYS);
            return today_rank;
        } else {
            ops.increment(todayRankKey(), 1);
            return (Integer) ops.get(todayRankKey());
        }
    }

    public String getNo(int accountId, String noType) {
        StringBuffer sb = new StringBuffer();
        sb = sb.append(DateHelper.formatyyMDHMS(new Date())); //当前时间
        sb = sb.append(String.format("%04d", getTodayRank() % 9997));
        sb = sb.append(String.format("%02d", accountId % 20));
        String no = noType + sb.toString();
        return no;
    }

    public static String todayRankKey() {
        String today = DateHelper.formatYMD(new Date());
        return "today_rank_" + today;
    }

}
